package org.example.myleet.learn.counter;

import java.util.concurrent.RecursiveTask;

public class EvenCounter extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 1000000;

    private final int[] numbers;
    private final int from;
    private final int to;

    public EvenCounter(int[] numbers, int from, int to) {
        this.numbers = numbers;
        this.from = from;
        this.to = to;
    }

    @Override
    protected Integer compute() {
        int result = 0;
        if (to - from <= THRESHOLD) {
            for (int i = from; i < to; ++i) {
                if ((numbers[i] & 1) == 0) {
                    ++result;
                }
            }
        } else {
            int mid = (from + to) >>> 1;
            EvenCounter leftCounter = new EvenCounter(numbers, from, mid);
            EvenCounter rightCounter = new EvenCounter(numbers, mid, to);
            invokeAll(leftCounter, rightCounter);
            result = leftCounter.join() + rightCounter.join();
        }
        return result;
    }
}
